//#include"mgepch.h"
#include"OpenGLTexture.h"
#include"glad/glad.h"
#include"stb_image.h"

namespace myMiniEngine {

	OpenGLTexture2D::OpenGLTexture2D(const std::string& _path) : path(_path) {
		int _width, _height, _channels;
		stbi_set_flip_vertically_on_load(1);
		stbi_uc* data = stbi_load(path.c_str(), &_width, &_height, &_channels, 0);
		MGE_CORE_ASSERT(data, "Failed to load image!");
		width = _width;
		height = _height;

		GLenum internalFormat = 0, dataFormat = 0;
		if (_channels == 4)
		{
			internalFormat = GL_RGBA8;
			dataFormat = GL_RGBA;
		}
		else if (_channels == 3)
		{
			internalFormat = GL_RGB8;
			dataFormat = GL_RGB;
		}

		MGE_CORE_ASSERT(internalFormat & dataFormat, "Format not supported");

		glCreateTextures(GL_TEXTURE_2D, 1, &rendererID);
		glTextureStorage2D(rendererID, 1, internalFormat, width, height);

		glTextureParameteri(rendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTextureParameteri(rendererID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

		glTextureSubImage2D(rendererID, 0, 0, 0, width, height, dataFormat, GL_UNSIGNED_BYTE,data);

		stbi_image_free(data);
	}

	OpenGLTexture2D::~OpenGLTexture2D() {
		glDeleteTextures(1, &rendererID);
	}

	 void OpenGLTexture2D::Bind(uint32_t slot) const {
		 glBindTextureUnit(slot, rendererID);
	}

}